package cn.yeamin.ms.controller.admin.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import cn.yeamin.ms.commons.JsonResult;
import cn.yeamin.ms.commons.PaginationResult;
import cn.yeamin.ms.controller.support.BaseController;
import cn.yeamin.ms.service.impl.RoleService;
import cn.yeamin.ms.service.impl.UserService;
import cn.yeamin.ms.utils.IsEmptyUtils;
import cn.yeamin.ms.utils.MD5Utils;
import cn.yeamin.ms.vo.Role;
import cn.yeamin.ms.vo.User;

/**
 * @packageName: 包名: cn.yeamin.ms.controller.admin.system
 * @classDesc: 类功能描述:(用户管理)
 * @author: Administrator
 * @createTime: 2017/7/27 10:08
 * @version: v1.0
 * @copyright:奕明(上海)影视传媒有限公司
 */
@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private RoleService roleService;
    

    @GetMapping(value = { "/", "/index" })
    public String index() {
        return "admin/user/index";
    }

    
    @PostMapping(value = { "/list" })
    @ResponseBody
    public PaginationResult list(
            @RequestParam(value="pageSize",defaultValue = "3") Integer pageSize,
            @RequestParam(value="pageNumber",defaultValue = "1") Integer pageNumber,
            @RequestParam(value="searchText",required=false) String searchText,
            @RequestParam(value="sortOrder",defaultValue = "ASC") String sortOrder) {
    	 List<String> property = null;
    	 if(!IsEmptyUtils.isEmptyForStr(searchText)) {
    		    property = new ArrayList<String>();
    	    	property.add("userName");
    	    	property.add("nickName");
    	    	property.add("telephone");
    	    	property.add("email");
    	 }
        PageInfo<User> info = userService.queryPageListOrderBy(pageNumber,pageSize,User.class,"create_time " +sortOrder,searchText,property);
        List<User> list = info.getList();
        if(!IsEmptyUtils.isEmptyForListOrSet(list)) {
        	for (User user : list) {
        		Set<Role> roles = roleService.findRoleByUserId(user.getId());
        		user.setRoles(roles);
        	}
        }
        return new PaginationResult(info.getTotal(),list);
    }
    
	@GetMapping(value = "/add")
	public String add() {
		return "admin/user/form";
	}

    @PostMapping(value= {"/edit"})
    @ResponseBody
    public JsonResult edit(@RequestParam("birthday") String birthday,User user){
        try {
        	User loginUser = getCurrentUser();
            if (user != null && user.getId() == null) {
            	user.setPassword(MD5Utils.md5(user.getTelephone().substring(user.getTelephone().length() - 6)));
            	user.setStatus(1);
            	user.setCreatedBy(loginUser.getUserName());
            	user.setUpdatedBy(loginUser.getUserName());
                userService.save(user);
            } else {
            	user.setPassword(null);
            	user.setCreatedBy(null);
            	user.setUpdatedBy(loginUser.getUserName());
                userService.updateSelective(user);
            }
            return JsonResult.success();
        } catch (Exception e) {
        	return JsonResult.failure("服务器异常,请稍后操作!");
        }
    }
    

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@PathVariable Long id,ModelMap map) {
		User user = userService.queryById(id);
		map.put("user", user);
		return "admin/user/form";
	}
    
	

	@GetMapping(value = "/grant/{id}")
	public String grant(@PathVariable Long id, ModelMap map) {
		User user = userService.queryById(id);
		map.put("user", user);
		Set<Role> set = roleService.findRoleByUserId(id);
		List<Long> roleIds = new ArrayList<Long>();
		for (Role role : set) {
			roleIds.add(role.getId());
		}
		map.put("roleIds", roleIds);
		List<Role> roles = roleService.queryAll();
		map.put("roles", roles);
		return "admin/user/grant";
	}
	
	
	@ResponseBody
	@PostMapping("/grant/{id}")
	public JsonResult grant(@PathVariable Long id,Long[] roleIds, ModelMap map) {
		try {
			userService.grant(id,roleIds);
		} catch (IllegalStateException e) {
			e.printStackTrace();
        	return JsonResult.failure(e.getMessage());
        }catch (Exception e) {
        	e.printStackTrace();
        	return JsonResult.failure("服务器异常,请稍后操作!");
        }
		return JsonResult.success();
	}
	
	@RequestMapping(value = "/updatePwd", method = RequestMethod.GET)
	public String updatePwd() {
		return "admin/user/updatePwd";
	}
	
	@RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult updatePwd(String oldPassword, String password1, String password2) {
		try {
			User user = getCurrentUser();
			if(user== null){
				return JsonResult.failure("您尚未登录");
			}
			userService.updatePwd(user,oldPassword, password1, password2);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.failure(e.getMessage());
		}
		return JsonResult.success();
	}
	
	@PostMapping(value = "/delete/{id}")
	@ResponseBody
	public JsonResult delete(@PathVariable Long id) {
		try {
			userService.deleteById(id);
		} catch (Exception e) {
			e.printStackTrace();
			JsonResult.failure("服务器异常,请稍后操作!");
		}
		return JsonResult.success();
	}
    


}
